
package guoan.web.weixin;

import guoan.core.common.WebConfig;
import guoan.domain.RandomKey;
import guoan.domain.Train;
import guoan.service.RandomKeyService;
import guoan.service.TrainService;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.common.base.Preconditions;

@Controller
@RequestMapping("/weixin/randomKey")
public class WeiXinRandomKeyController {
    protected final Logger log = LoggerFactory.getLogger(getClass());

    @Autowired
    private RandomKeyService randomKeyService;
    @Autowired
    private TrainService trainService;

    /** 跳转到考试主页 */
    @RequestMapping(value = "index", method = RequestMethod.GET)
    public String index(HttpServletRequest request, Model model, Long type){
        Preconditions.checkNotNull(type, "参数错误");
        Preconditions.checkArgument(
                (type.intValue() != 2 || type.intValue() != 3|| type.intValue() != 1), "参数错误");
        HttpSession session = request.getSession();
        if(session
                .getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY)==null){
        	return "redirect:/weixin/train/oauthTrain";
        }
        String openid = (String) session
                .getAttribute(WebConfig.SESSION_WEIXIN_OPENID_KEY);
        Train train = trainService.findByOpenid(openid);
        // 如果教练没绑定过，则去绑定
        if (train == null) {
        	return "redirect:/weixin/train/oauthTrain";
        }
        List<RandomKey> randomKeys = randomKeyService
                .findByTrainIdAndCoachTypeAndIsUse(train.getId(), type, 0L);
        model.addAttribute("randomKeys", randomKeys);
        return "/weixin/randomKey/index";
    }

    @RequestMapping(value = "show/{id}", method = RequestMethod.GET)
    public String show(@PathVariable("id") Long id,Model model){
        RandomKey randomKey = randomKeyService.findOne(id);
        model.addAttribute("randomKey", randomKey);
        return "/weixin/randomKey/show";
    }
}
